<template>
  <div class="user-management">
    <!-- 搜索和操作栏 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="18">
        <el-form :model="searchForm" label-width="80px" :inline="true">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="searchForm.realname" placeholder="请输入真实姓名" />
          </el-form-item>
          <el-form-item label="所属科室">
            <el-select v-model="searchForm.deptid" placeholder="请选择科室" style="width: 180px">
              <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchUser">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6" class="text-right">
        <el-button type="primary" @click="openAddDialog">添加用户</el-button>
        <el-button type="danger" @click="batchDelete" v-if="selectedIds.length > 0">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table
        :data="userList"
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="realname" label="真实姓名" width="120" />
      <el-table-column prop="deptName" label="所属科室" width="150" />
      <el-table-column prop="usertypeName" label="用户类型" width="120" />
      <el-table-column prop="doctitleName" label="职称" width="120" />
      <el-table-column prop="isscheduling" label="参与排班" width="100" :formatter="formatIsScheduling" />
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="warning" @click="openPasswordDialog(scope.row.id)">修改密码</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑用户' : '添加用户'"
        width="500px"
    >
      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="用户类型" prop="usetype">
          <el-select v-model="form.usetype" placeholder="请选择用户类型" style="width: 100%">
            <el-option v-for="type in userTypeOptions" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="医生职称" prop="doctitleid" v-if="form.usetype === 3">
          <el-select v-model="form.doctitleid" placeholder="请选择职称" style="width: 100%">
            <el-option v-for="title in titleOptions" :key="title.id" :label="title.name" :value="title.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属科室" prop="deptid">
          <el-select v-model="form.deptid" placeholder="请选择所属科室" style="width: 100%">
            <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="挂号级别" prop="registleid" v-if="form.usetype === 3">
          <el-select v-model="form.registleid" placeholder="请选择挂号级别" style="width: 100%">
            <el-option v-for="level in registLevelOptions" :key="level.id" :label="level.name" :value="level.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="参与排班" prop="isscheduling">
          <el-radio-group v-model="form.isscheduling">
            <el-radio :label="'是'">是</el-radio>
            <el-radio :label="'否'">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 密码修改对话框 -->
    <el-dialog
        v-model="passwordDialogVisible"
        title="修改密码"
        width="350px"
    >
      <el-form
          :model="passwordForm"
          :rules="passwordRules"
          ref="passwordFormRef"
          label-width="80px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 加载中遮罩 -->
    <div v-if="loading" class="loading-mask">
      <el-loading v-model="loading" text="加载中..." spinner="el-icon-loading"></el-loading>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from 'axios'

// API 基础URL
const API_BASE_URL = 'http://localhost:8080'

// 状态管理
const loading = ref(false)
const errorMessage = ref('')

// 搜索表单
const searchForm = reactive({
  username: '',
  realname: '',
  deptid: null
})

// 表格数据
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])
const currentUserId = ref(null)

// 对话框状态
const dialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const passwordFormRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  username: '',
  password: '',
  realname: '',
  usertype: 1,
  doctitleid: null,
  deptid: null,
  registleid: null,
  isscheduling: '否'
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符', trigger: 'blur' }
  ],
  realname: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  usetype: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  deptid: [
    { required: true, message: '请选择所属科室', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
})

const passwordRules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
})

// 静态数据（实际项目中应从后端获取）
const deptList = ref([
  { id: 1, name: '内科' },
  { id: 2, name: '外科' },
  { id: 3, name: '儿科' },
  { id: 4, name: '妇产科' },
  { id: 5, name: '急诊科' },
  { id: 6, name: '检验科' },
  { id: 7, name: '放射科' }
])

const userTypeOptions = ref([
  { value: 1, label: '管理员' },
  { value: 2, label: '护士' },
  { value: 3, label: '医生' },
  { value: 4, label: '药剂师' }
])

const titleOptions = ref([
  { id: 1, name: '主任医师' },
  { id: 2, name: '副主任医师' },
  { id: 3, name: '主治医师' },
  { id: 4, name: '住院医师' }
])

const registLevelOptions = ref([
  { id: 1, name: '普通号' },
  { id: 2, name: '专家号' },
  { id: 3, name: '特需号' },
  { id: 4, name: '急诊号' }
])

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList()
})

// 获取用户列表
async function fetchUserList() {
  loading.value = true
  errorMessage.value = ''

  try {
    const response = await axios.get(`${API_BASE_URL}/user/list`)

    if (Array.isArray(response.data)) {
      userList.value = response.data.map(user => ({
        ...user,
        deptName: deptList.value.find(d => d.id === user.deptid)?.name || '-',
        usertypeName: userTypeOptions.value.find(t => t.value === user.usetype)?.label || '-',
        doctitleName: titleOptions.value.find(t => t.id === user.doctitleid)?.name || '-'
      }))
      total.value = response.data.length
    } else {
      errorMessage.value = '接口返回数据格式错误'
      ElMessage.error(errorMessage.value)
    }
  } catch (error) {
    handleApiError(error, '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索用户
function searchUser() {
  currentPage.value = 1
  fetchUserList()
}

// 处理分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  fetchUserList()
}

// 处理当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
  fetchUserList()
}

// 处理选择变化
function handleSelectionChange(rows) {
  selectedIds.value = rows.map(row => row.id)
}

// 打开添加对话框
function openAddDialog() {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true

  // 确保对话框完全打开后聚焦到用户名输入框
  nextTick(() => {
    const usernameInput = document.querySelector('.el-dialog input[placeholder="请输入用户名"]')
    usernameInput?.focus()
  })
}

// 打开编辑对话框
function openEditDialog(row) {
  isEdit.value = true
  resetForm()

  // 复制用户数据到表单
  Object.assign(form, {
    ...row,
    // 转换 isscheduling 为字符串类型
    isscheduling: row.isscheduling ? '是' : '否'
  })

  dialogVisible.value = true
}

// 打开密码修改对话框
function openPasswordDialog(id) {
  currentUserId.value = id
  resetPasswordForm()

  passwordDialogVisible.value = true
  nextTick(() => {
    const oldPasswordInput = document.querySelector('.el-dialog input[placeholder="请输入原密码"]')
    oldPasswordInput?.focus()
  })
}

// 重置表单
function resetForm() {
  form.id = ''
  form.username = ''
  form.password = ''
  form.realname = ''
  form.usetype = 1
  form.doctitleid = null
  form.deptid = null
  form.registleid = null
  form.isscheduling = '否'

  formRef.value?.resetFields()
}

// 重置密码表单
function resetPasswordForm() {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''

  passwordFormRef.value?.resetFields()
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return

  formRef.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        const url = `${API_BASE_URL}/user/saveOrUpdate`
        const response = await axios.post(url, form)

        if (response.data) {
          ElMessage.success(isEdit.value ? '更新用户成功' : '添加用户成功')
          dialogVisible.value = false
          fetchUserList()
        } else {
          ElMessage.error(isEdit.value ? '更新用户失败' : '添加用户失败')
        }
      } catch (error) {
        handleApiError(error, isEdit.value ? '更新用户失败' : '添加用户失败')
      } finally {
        loading.value = false
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 修改密码
async function updatePassword() {
  if (!currentUserId.value) {
    ElMessage.error('操作失败，请重试')
    return
  }

  if (!passwordFormRef.value) return

  passwordFormRef.value.validate(async valid => {
    if (valid) {
      loading.value = true

      try {
        const url = `${API_BASE_URL}/user/updatePassword/${currentUserId.value}`
        const response = await axios.post(url, {
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })

        if (response.data) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
        } else {
          ElMessage.error('密码修改失败：原密码不正确')
        }
      } catch (error) {
        handleApiError(error, '密码修改失败')
      } finally {
        loading.value = false
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 删除用户 - 修改为使用 DELETE 请求
async function deleteUser(id) {
  try {
    const confirmResult = await ElMessageBox.confirm(
        '确定要删除该用户吗？此操作不可恢复',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    if (confirmResult === 'confirm') {
      loading.value = true
      const url = `${API_BASE_URL}/user/deleteById/${id}`
      // 使用 DELETE 方法
      const response = await axios.delete(url)

      if (response.data) {
        ElMessage.success('删除用户成功')
        fetchUserList()
      } else {
        ElMessage.error('删除用户失败')
      }
    }
  } catch (error) {
    if (error.name !== 'CancelError') {
      handleApiError(error, '删除用户失败')
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
async function batchDelete() {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的用户')
    return
  }

  try {
    const confirmResult = await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedIds.value.length} 个用户吗？此操作不可恢复`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    if (confirmResult === 'confirm') {
      loading.value = true
      const url = `${API_BASE_URL}/user/batchDelete`
      const response = await axios.post(url, { ids: selectedIds.value })

      if (response.data) {
        ElMessage.success('批量删除成功')
        selectedIds.value = []
        fetchUserList()
      } else {
        ElMessage.error('批量删除失败')
      }
    }
  } catch (error) {
    if (error.name !== 'CancelError') {
      handleApiError(error, '批量删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 格式化参与排班字段
function formatIsScheduling(row) {
  return row.isscheduling === '是' ? '是' : '否'
}

// 统一处理API错误
function handleApiError(error, defaultMessage) {
  console.error('API请求错误:', error)

  if (error.response) {
    // 服务器返回错误状态码
    const { status, statusText, data } = error.response

    if (status === 404) {
      errorMessage.value = '接口不存在，请检查后端路由配置'
    } else if (status === 500) {
      errorMessage.value = '服务器内部错误，请联系管理员'
    } else if (data && data.message) {
      errorMessage.value = data.message
    } else {
      errorMessage.value = `${status} ${statusText}`
    }
  } else if (error.code === 'ERR_CONNECTION_REFUSED') {
    // 连接被拒绝（服务器未启动）
    errorMessage.value = '无法连接到服务器，请确认后端服务已启动'
  } else if (error.code === 'ERR_NETWORK') {
    // 网络错误
    errorMessage.value = '网络连接失败，请检查网络设置'
  } else {
    // 其他错误
    errorMessage.value = error.message || defaultMessage
  }

  ElMessage.error(errorMessage.value)
}

// 监听用户类型变化，动态显示/隐藏职称和挂号级别字段
watch(() => form.usetype, (newVal) => {
  if (newVal !== 3) {
    form.doctitleid = null
    form.registleid = null
  }
})
</script>

<style scoped>
/* 样式部分保持不变 */
</style>